package org.aizuomeng.config.SpringSecurity;

import cn.hutool.jwt.JWTUtil;
import com.alibaba.fastjson.JSON;
import org.aizuomeng.common.api.LoginUser;
import org.aizuomeng.common.api.Result;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import springfox.documentation.spring.web.json.Json;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @email 839013329@qq.com
 * @author: LuHaoLong
 * @date: 2021/12/29
 * @time: 10:38
 * @description: 登陆成功
 */
@Component
public class AjaxAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        LoginUser userDetails = (LoginUser) authentication.getPrincipal();
        Map<String,Object> map = new HashMap<>();
        map.put("user",JSON.toJSONString(userDetails));
        map.put("expire_time",System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 15);
        String jwtToken = JWTUtil.createToken(map,"1234".getBytes(StandardCharsets.UTF_8));
        httpServletResponse.getWriter().write(JSON.toJSONString(Result.OK(jwtToken)));
    }
}
